package com.detrum.detrumdx.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.detrum.DownloadReceiver;
import com.detrum.base.BaseFinal;
import com.detrum.base.BaseStatic;
import com.detrum.base.ServiceStatic;
import com.detrum.detrumdata.service.USBConnetService;
import com.detrum.detrumdata.service.UsbServiceCall1;
import com.detrum.detrumdx.base.DeviceStatic;
import com.detrum.detrumdx.fragment.DeviceFragment;
import com.detrum.detrumdx.fragment.MediaFragment;
import com.detrum.detrumdx.fragment.SelectPopupwindow;
import com.detrum.detrumdx.fragment.ShopFragment;
import com.detrum.service.DownloadReceiveCall;
import com.detrum.sportcamera.SportActivity;
import com.detrum.sportcamera.service.WifiService;
import com.detrum.sportcamera.service.WifiServiceCallback;
import com.detrum.usbdevice.UAVPreviewActivity;
import com.detrum.utils.HttpDataManager;
import com.detrum.utils.LogUtils;
import com.detrum.utils.MyMethod;
import com.detrum.utils.MyOkHttpHelper;
import com.detrum.utils.PermissionCall;
import com.detrum.utils.PermissionRegister;

import java.io.File;

import com.detrum.detrumdx.R;

import static com.detrum.base.BaseStatic.NetPath;
import static com.detrum.base.BaseStatic.RecordToSD;
import static com.detrum.base.BaseStatic.savaInfoToSD;

import com.detrum.wifidevice.bean.WifiInfoBean;


public class MainActivity extends AppCompatActivity implements View.OnClickListener, DeviceFragment.OnFragmentInteractionListener, MediaFragment.OnFragmentInteractionListener
        , ShopFragment.OnFragmentInteractionListener, PermissionCall, DownloadReceiveCall {
    private Context context;
    private PermissionRegister permissionRegister;
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;
    private DeviceFragment deviceFragment;
    private MediaFragment mediaFragment;
    private ShopFragment shopFragment;
    private RadioButton mRbDevice, mRbMe, rb_media;
    private ImageView loading;
    private FrameLayout fl_fragments_content, selectFrame;
    private RelativeLayout activity_main;

    private boolean isResume;
    private String currentDevice;
    private SelectPopupwindow selectPopupwindow;

    private DownloadReceiver downloadReceiver;
    private TextView exit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        savaInfoToSD(MyMethod.getDateTimeByMillisecond(System.currentTimeMillis(),"yyyy-MM-dd-hh-mm")+"\nMainActivity onCreate");
        BaseStatic.isMainLaunch = true;
        permissionRegister = new PermissionRegister(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            CheckPremission();
        } else {
            getVersion(VerFlag.MAIN);
        }
        fragmentManager = getSupportFragmentManager();
        exit = findViewById(R.id.exit);
        initView();
        initConn();
    }

    @Override
    protected void onResume() {
        super.onResume();
        savaInfoToSD("MainActivity onResume");
        String source = getIntent().getStringExtra("flag");
        if (source != null && source.equals("welcome")) {
            pageFlag = 0;
        }
        if(!isSaveInstance){
            initFragment();
        }
        isResume = true;
        startService(usbIntent);
        usbConn = new UsbConn();
        bindService(usbIntent, usbConn, BIND_AUTO_CREATE);
        if(ServiceStatic.isWifiDeviceConnect){
            exit.setText("");
            exit.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        savaInfoToSD("MainActivity onPause");
        exit.setText("");
        exit.setVisibility(View.GONE);
        isResume = false;
        if (ServiceStatic.isLaunchUsbService) {
            UnBindService(DeviceStatic.Digifax);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        savaInfoToSD("MainActivity onDestroy");
        closeAll();
        RecordToSD();
        BaseStatic.isMainLaunch = false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == BaseFinal.MediaFragment){
            BaseFinal.MediaFragmentRequest = false;
        }
    }

    private Handler handler = new Handler();
    private long exitTime;
    private int isLocal;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(pageFlag==1){
                if(isEdit){
                    mediaFragment.onButtonPressed();
                    return true;
                }
                if(isLocal!=0){
                    mediaFragment.onBackDeviceList();
                    return true;
                }
            }
            long exitTime2 = System.currentTimeMillis();
            if (exitTime != 0) {
                if ((exitTime2 - exitTime) < 2500) {
                    finish();
                    return true;
                }
            }
            exit.setText(R.string.app_exit);
            exit.setVisibility(View.VISIBLE);
            exitTime = System.currentTimeMillis();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit.setVisibility(View.GONE);
                }
            }, 2500);
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    private void closeAll() {
        if (ServiceStatic.isBluetoothServiceStart) {
            // TODO: 2018/5/24 蓝牙相关
           /* if (bluetoothConn != null) {
                unbindService(bluetoothConn);
            }
            stopService(bluetoothIntent);*/
        }
        // TODO: 2018/5/4 wifi模块相关 
        if (ServiceStatic.isWifiServiceStart && WifiIntent != null) {
            if (wifiConn != null) {
                unbindService(wifiConn);
            }
            stopService(WifiIntent);
        }
        if (ServiceStatic.isLaunchUsbService) {
            if (usbConn != null) {
                unbindService(usbConn);
            }
            stopService(usbIntent);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void CheckPremission() {
        permissionRegister.CheckPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, R.string.sdcard_msg, 1, this);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        activity_main = findViewById(R.id.activity_main);
        mRbDevice = findViewById(R.id.rb_device);
        mRbMe = findViewById(R.id.rb_me);
        rb_media = findViewById(R.id.rb_media);
        mRbDevice.setOnClickListener(this);
        mRbMe.setOnClickListener(this);
        rb_media.setOnClickListener(this);
        mRbDevice.setChecked(true);
        loading = findViewById(R.id.loading);
        fl_fragments_content = findViewById(R.id.fl_fragments_content);
        selectFrame = findViewById(R.id.selectFrame);
        fl_fragments_content.setOnClickListener(this);
        selectPopupwindow = new SelectPopupwindow();
    }

    /**
     * 初始化fragment
     */
    private void initFragment() {
        if(deviceFragment==null){
            deviceFragment = DeviceFragment.newInstance();
        }
        if(mediaFragment==null){
            mediaFragment = MediaFragment.newInstance();
        }
        if(shopFragment==null){
            shopFragment = ShopFragment.newInstance();
        }
        if (pageFlag == 0) {
            ShowFragment(deviceFragment);
        } else if (pageFlag == 1) {
            ShowFragment(mediaFragment);
        } else if (pageFlag == 2) {
            ShowFragment(shopFragment);
        }

    }

    private Intent usbIntent;
    private UsbConn usbConn;
    private USBConnetService usbService;

    @Override
    public void downloadDeviceFinish(String path) {
        if (path.endsWith("DtSysFW.bin")) {
            new AlertDialog.Builder(this)
                    .setMessage(R.string.device_download_finish_IWT)
                    .setNegativeButton(R.string.updata, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (usbService != null && ServiceStatic.isAccessoryConnect) {
                                usbService.updataDevice();
                            }
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create()
                    .show();
        } else if (path.endsWith("FpvCamSysFW.bin")) {
            new AlertDialog.Builder(this)
                    .setMessage(R.string.device_download_finish_DCAM)
                    .setNegativeButton(R.string.updata, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create()
                    .show();
        }
    }

    @Override
    public void downloadDeviceProgress(int progress, int length) {

    }

    @Override
    public void downloadAppProgress(int progress, int length) {

    }

    @Override
    public void downloadFail() {
        if(isResume){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MyMethod.ShowDialog(MainActivity.this,R.string.device_file_exception);
                }
            });
        }
    }

    private class UsbConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            usbService = ((USBConnetService.UsbBinder) service).getService();
            usbService.setUsbServiceCall1(new UsbServiceCall1() {
                @Override
                public void connect() {

                }

                @Override
                public void disconnect() {
                    if (ServiceStatic.isLaunchUsbService) {
                        MainActivity.this.stopService(usbIntent);
                    }
                    if (!isResume) {
                        return;
                    }
                    if (pageFlag == 0) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                deviceFragment.usbDisconnect();
                            }
                        });
                    }
                }

                @Override
                public void onVersion(boolean isSuccess) {
                    if (pageFlag == 0) {
                        deviceFragment.setList(isSuccess);
                    }
                }
            });
            usbService.startAccessory();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    private void initConn() {
        // TODO: 2018/5/24 蓝牙相关
        /*bluetoothConn = new BluetoothConn();
        resultList = new ArrayList<>();*/
        // TODO: 2018/5/4 wifi模块相关
        wifiConn = new WifiConn();
        usbIntent = new Intent(this, USBConnetService.class);
        downloadReceiver = new DownloadReceiver();
        downloadReceiver.setDownloadReceiveCall(this);
    }

    private void ShowFragment(Fragment fragment) {
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fl_fragments_content, fragment);
        fragmentTransaction.commit();
    }

    @Override
    public void ScanWifi() {
        // TODO: 2018/5/4 wifi设备sport module相关
        if (wifiService == null) {
            WifiIntent = new Intent(context, WifiService.class);
            startService(WifiIntent);
            bindService(WifiIntent, wifiConn, BIND_AUTO_CREATE);
        } else {
            wifiService.ScanWifi();
        }
    }

    @Override
    public void startUsbPreview() {
        if (ServiceStatic.isAccessoryConnect) {
            MyMethod.toActivity(context, UAVPreviewActivity.class);
            UnBindService(DeviceStatic.Digifax);
        }
    }

    @Override
    public void startPreview() {

    }

    @Override
    public void getVersion(VerFlag flag) {
        if (flag == VerFlag.MAIN) {
            MaingetVersion();
        }
    }

    @Override
    public void Cancel() {
        loading.setVisibility(View.GONE);
    }

    private void MaingetVersion() {
        MyOkHttpHelper.getInstance(context).doGet(NetPath, null).excute(1, new MyOkHttpHelper.OKCallBack() {
            @Override
            public void onFailure(int message) {
                if (loading != null) {
                    loading.setVisibility(View.GONE);
                    if (!ServiceStatic.isWifiServiceStart && isResume) {
                        //new AlertDialog.Builder(context).setTitle(com.detrum.base.R.string.net_fault).setMessage(com.detrum.base.R.string.net_show).create().show();
                    }
                }
            }

            @Override
            public void onInternetFail() {
                if (loading != null) {
                    loading.setVisibility(View.GONE);
                    if (isResume) {
                        //new AlertDialog.Builder(context).setTitle(com.detrum.base.R.string.net_fault).setMessage(com.detrum.base.R.string.net_show).create().show();
                    }
                }
            }

            @Override
            public void onResponse(String message) {
                if (message != null) {
                    loading.setVisibility(View.GONE);
                    HttpDataManager.getInstance().getVersion(context, message, new HttpDataManager.HttpManagerCall() {
                        @Override
                        public void success() {
                            LogUtils.i(BaseStatic.appNetCode + "---------------" + BaseStatic.appCode);
                            if (isResume) {
                                if (BaseStatic.appNetCode > BaseStatic.appCode) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            MyMethod.ShowDiaLogDownload(context, BaseStatic.appNetMessage);
                                        }
                                    });
                                } else {
                                    String[] strs = BaseStatic.appNetPath.split("/");
                                    String name = strs[strs.length - 1];
                                    File file = new File(BaseStatic.path, name);
                                    if (file != null) {
                                        file.delete();
                                    }
                                }
                            }
                        }

                        @Override
                        public void fail(int msg) {
                            if (isResume) {
                                //首页获取失败没有提示
                                //MyMethod.ShowDialog(context, msg);
                            }
                        }
                    });
                }
            }
        });
    }

    private int pageFlag;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rb_device:
                pageFlag = 0;
                ShowFragment(deviceFragment);
                BaseFinal.MediaFragmentRequest=true;
                break;
            case R.id.rb_media:
                pageFlag = 1;
                BaseFinal.MediaFragmentRequest=true;
                ShowFragment(mediaFragment);
                break;
            case R.id.rb_me:
                pageFlag = 2;
                ShowFragment(shopFragment);
                BaseFinal.MediaFragmentRequest=true;
                break;

        }
    }

    private boolean isSaveInstance;
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        isSaveInstance = true;//save后有部分操作不能进行。如fragmentTransaction.commit();
        LogUtils.i("MainActivity onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        LogUtils.i("MainActivity onRestoreInstanceState");
        isSaveInstance = false;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
    private boolean isEdit;
    @Override
    public void onEdit(boolean isEdit) {
        this.isEdit = isEdit;
    }

    @Override
    public void onLocal(int Local) {
        isLocal = Local;
    }

    @Override
    public void StartDetails(String name) {
        //进入对应设备的详情页面
        if (name.equals(DeviceStatic.HardDeck)) {

        } else if (name.equals(DeviceStatic.SportCamera)) {
            // TODO: 2018/5/23 测试关闭
            //MyMethod.toActivity(context, PreviewActivity.class);
        } else if (name.equals(DeviceStatic.Digifax)) {

        } else if (name.equals(DeviceStatic.FeiKong)){
           /* MyMethod.toActivity(context, FeiKongActivity.class);
            UnBindService(DeviceStatic.Digifax);*/
        }
    }

    @Override
    public void EnterDevice(String name) {
        if (name.contains("IWT")) {
            LogUtils.e("点击进入模数转换预览界面");
            if (!ServiceStatic.isAccessoryConnect) {
                MyMethod.ShowDialog(context, R.string.usb_exception);
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                permissionRegister.CheckPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, R.string.sdcard_msg, 2, this);
            } else {
                startUsbPreview();
            }
        } else if (name.contains("DCAM")) {
            LogUtils.e("点击开启wifi搜索附近相机设备");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                permissionRegister.CheckPermission(Manifest.permission.ACCESS_FINE_LOCATION, R.string.wifi_msg, 4, this);
            } else {
                ScanWifi();
            }
        } else if (name.equals("手持云台")) {
            // TODO: 2018/5/24 蓝牙相关
            /*LogUtils.e("点击开启蓝牙搜索附近手持设备");
            bluetoothIntent = new Intent(context, BluetoothService.class);
            context.startService(bluetoothIntent);
            context.bindService(bluetoothIntent, bluetoothConn, BIND_AUTO_CREATE);*/
        }
    }

    private void UnBindService(String name) {
        // TODO: 2018/5/4 wifi模块相关 
        if (name.equals(DeviceStatic.HardDeck)) {
            // TODO: 2018/5/24 蓝牙相关
           /* if (bluetoothConn != null) {
                unbindService(bluetoothConn);
                bluetoothConn = null;
            }*/
        } else if (name.equals(DeviceStatic.Wifi)) {
            if (wifiConn != null) {
                unbindService(wifiConn);
                wifiConn = null;
            }
        } else if (name.equals(DeviceStatic.Digifax)) {
            if (usbConn != null) {
                unbindService(usbConn);
                usbConn = null;
            }
        }
    }

    @Override
    public void downloadVersion() {
        // TODO: 2018/5/4 wifi模块相关 
        if (previous != -1 && wifiService != null) {
            wifiService.ConnectOldWifi(previous);
            previous = -1;
            return;
        }
        loading.setVisibility(View.VISIBLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permissionRegister.CheckPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, R.string.download_msg, 1, this);
        } else {
            getVersion(VerFlag.MAIN);
        }
    }

    // TODO: 2018/5/24 蓝牙相关
   /* private Intent bluetoothIntent;
    private BluetoothConn bluetoothConn;
    private BluetoothService mBluetoothService;
    private List<ScanResult> resultList;
    private boolean isSearchBluetooth;

    class BluetoothConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtils.e("BluetoothConn");
            mBluetoothService = ((BluetoothService.BluetoothBinder) service).getService();
            mBluetoothService.setScanCallback(callback);
            mBluetoothService.scanDevice();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    //蓝牙扫描结果，发现连接结果返回
    private BluetoothService.Callback callback = new BluetoothService.Callback() {
        @Override
        public void onStartScan() {
            //开始扫描
            resultList.clear();
            loading.setVisibility(View.VISIBLE);
            isSearchBluetooth = true;
        }

        @Override
        public void onScanning(ScanResult result) {
            //扫描过程中
            resultList.add(result);
        }

        @Override
        public void onScanComplete() {
            //扫描结束
            isSearchBluetooth = false;
            loading.setVisibility(View.GONE);
            BluetoothInfoBean bean = new BluetoothInfoBean();
            bean.setResultList(resultList);
            Gson gson = new Gson();
            String json = gson.toJson(bean);
            selectPopupwindow.init(context, json, DeviceStatic.Bluetooth, activity_main, new SelectPopupwindow.PopupwindowCall() {
                @Override
                public void onItem(ScanResult scanResult) {
                    *//*mBluetoothService.setResult(scanResult);
                    mBluetoothService.connectDevice(scanResult);*//*
                    MyMethod.toActivity(context, CameraPreview.class);
                }

                @Override
                public void onItem(WifiInfoBean.DataBean wifiBean) {

                }

                @Override
                public void dismiss() {
                    UnBindService(currentDevice);//断开蓝牙service绑定
                }
            });
            currentDevice = DeviceStatic.HardDeck;
        }

        @Override
        public void onConnecting() {
            //开始连接设备
            loading.setVisibility(View.VISIBLE);
        }

        @Override
        public void onConnectFail() {
            //连接设备失败
            loading.setVisibility(View.GONE);
        }

        @Override
        public void onDisConnected() {
            //连接中断
            loading.setVisibility(View.GONE);
        }

        @Override
        public void onServicesDiscovered() {
            //连接成功 -- 发现服务
            loading.setVisibility(View.GONE);
            //MyMethod.toActivity(context, CameraPreview.class);
        }
    };*/
    // TODO: 2018/5/4 wifi模块相关 
    private Intent WifiIntent;
    private WifiConn wifiConn;
    private WifiService wifiService;
    private int previous = -1;
    private WifiServiceCallback wifiServiceCallback = new WifiServiceCallback() {
        @Override
        public void scanResult(String json) {
            selectPopupwindow.init(context, json, DeviceStatic.Wifi, activity_main, new SelectPopupwindow.PopupwindowCall() {
                // TODO: 2018/5/24 蓝牙相关
                /*@Override
                public void onItem(ScanResult scanResult) {

                }*/

                @Override
                public void onItem(WifiInfoBean.DataBean wifiBean) {
                    wifiService.setWifiBean(wifiBean);
                    previous = wifiBean.getPrevious();
                    if (!wifiBean.isConnect()) {
                        wifiService.ConnectWifi(wifiBean.getSSID());
                        exit.setText(R.string.wifi_connecting);
                        exit.setVisibility(View.VISIBLE);
                        Connect connect = new Connect(wifiBean.getSSID());
                        handler.postDelayed(connect,2000);
                    } else {
                        ServiceStatic.isWifiDeviceConnect = true;
                        MyMethod.toActivity(context, SportActivity.class);
                    }
                }

                @Override
                public void dismiss() {
                    //UnBindService(currentDevice);//断开wifiservice绑定
                }
            });
            currentDevice = DeviceStatic.Wifi;
        }

        @Override
        public void scanFail() {
            //MyMethod.ShowDialog(context, "连接失败");
            if(isResume){
                exit.setText("");
                exit.setVisibility(View.GONE);
            }

        }

        @Override
        public void connectSuccess() {
            if(isResume){
                exit.setText("");
                exit.setVisibility(View.GONE);
            }
            MyMethod.toActivity(context, SportActivity.class);
        }

        @Override
        public void connectState(int state) {
            if(isResume){
                if(state == 2){
                    exit.setVisibility(View.VISIBLE);
                    exit.setText(R.string.wifi_connecting);
                }else if(state == 3){
                    exit.setVisibility(View.VISIBLE);
                    exit.setText(R.string.wifi_fail);
                }else if(state == 4){
                    exit.setVisibility(View.VISIBLE);
                    exit.setText("身份验证中");
                }else if(state == 5){
                    exit.setVisibility(View.VISIBLE);
                    exit.setText(R.string.wifi_ip);
                }else if(state == 0){
                    //exit.setVisibility(View.GONE);
                }else if(state == 1){
                    exit.setVisibility(View.GONE);
                }
            }
        }
    };

    private class Connect implements Runnable{
        String SSID;
        int num;
        public Connect(String SSID) {
            this.SSID = SSID;
        }

        @Override
        public void run() {
            String text = exit.getText().toString();
            if(text.equals(getResources().getString(R.string.wifi_connecting))){
                num++;
                if(num<2){
                    wifiService.ConnectWifi(SSID);
                    handler.postDelayed(this,2000);
                }else{
                    num=0;
                    exit.setText(R.string.wifi_fail);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            exit.setVisibility(View.GONE);
                        }
                    },1000);
                }
            }
        }
    }

    class WifiConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            wifiService = ((WifiService.WifiBinder) service).getService();
            wifiService.setWifiServiceCallback(wifiServiceCallback);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    wifiService.ScanWifi();
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                ScanWifi();
            } else if (permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {

            } else if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                startUsbPreview();
            }
        }
    }
}
